import { asyncRequestUserInfo, asyncRequestUpdateUserInfo } from "@/actions/userInfo";
import { UpdateUserInfo, UserInfo } from "@/types"
import { useDispatch, useSelector } from "react-redux"

export function useUserInfo() {
  const dispatch = useDispatch();
  const userInfo = useSelector<UserInfo, UserInfo>((state: any) => state.userInfo);
  /**
   * 设置用户信息
   */
  const setUserInfoFn = async (callback?: Function) => {
    const actionCreator: any = await asyncRequestUserInfo();
    dispatch((dispatch, getState) => {
      dispatch(actionCreator);
      let latestState = getState();
      let userId = latestState.userInfo ? latestState.userInfo.userId : "";
      callback && callback(userId);
    });

  }
  /**
   * 更新用户信息
   */
  const updateUserInfoFn = async (params: UpdateUserInfo) => {
    const actionCreator: any = await asyncRequestUpdateUserInfo(params);
    dispatch(actionCreator);
  }
  return {
    userInfo,
    setUserInfoFn,
    updateUserInfoFn,
  }
}